package algocasts;

public class P51_minSumOfPath {
    public int minSumOfPath2DArray(int[][] a) {
        int m = a.length, n = a[0].length;
        int[][] dp = new int[m][n];

        dp[0][0] = a[0][0];
        for (int i = 1; i < m; i++) dp[i][0] = dp[i - 1][0] + a[i][0];
        for (int j = 1; j < n; j++) dp[0][j] = dp[0][j - 1] + a[0][j];

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + a[i][j];
        return dp[m - 1][n - 1];
    }

    public int minSumOfPath1DArray(int[][] a) {
        int m = a.length, n = a[0].length;
        int[] dp = new int[n];

        dp[0] = a[0][0];
        for (int j = 1; j < n; j++) dp[j] = dp[j - 1] + a[0][j];
        for (int i = 1; i < m; i++) {
            dp[0] = dp[0] + a[i][0];
            for (int j = 1; j < n; j++)
                dp[j] = Math.min(dp[j], dp[j - 1]) + a[i][j];
        }
        return dp[n - 1];
    }
}
